Injecting Values Into a Service

Course- AngularJS >

Service

A service in AngularJS is a singleton JavaScript object which contains a set of functions. The functions contain whatever logic is necessary for the service to carry out its work.

AngularJS services are created using the service() function on a module. Here is an example:

function MyService() {
    this.doIt = function() {
        console.log("done");
    }
}


var myModule = angular.module("myModule", []);

myModule.service("myService", MyService);

As you can see, services are defined somewhat differently than factories and values. First of all, the service is defined as a separate, named function. That is because services in AngularJS are created using the new keyword. Thus, AngularJS will do this internally:

var theService = new MyService();

Apart from defining services as functions with functions inside, you add them to and use them with AngularJS just like you would with a value or function. You inject a service into a controller like this:

function MyService() {
    this.doIt = function() {
        console.log("done");
    }
}


var myModule = angular.module("myModule", []);

myModule.service("myService", MyService);


myModule.controller("MyController", function($scope, myService) {

    myService.doIt();

});

Injecting Values Into a Service

You can inject values into a service, just like you can inject values into controllers, or services into controllers etc. Here is an example:

var myModule = angular.module("myModule", []);

myModule.value  ("myValue"  , "12345");

function MyService(myValue) {
    this.doIt = function() {
        console.log("done: " + myValue;
    }
}

myModule.service("myService", MyService);

Notice how the parameter to the MyService function is named the same as the value registered on the module. Thus, the value will be injected into the service when it is created.